﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing;
using System.IO;

namespace AUV5.Common
{
    /// <summary>
    ///Class1 的摘要说明
    /// </summary>
    public static class ImageProcess
    {
        /// <summary>
        /// 将图片转为合适的尺寸
        /// </summary>
        /// <param name="imgpath">图片的虚拟路径（相对路径）</param>
        /// <param name="properwidth">目标宽度</param>
        /// <param name="properheight">目标高度</param>
        /// <param name="destpath">目标图片的存储路径</param>
        /// <param name="previewpath">中间图片的存储路径,null表示不存储中间图片</param>
        /// <param name="deleteSource">是否删除源文件</param>
        /// <returns></returns>
        public static void ImageToProperSize(string imgpath, int properwidth, int properheight, string destpath, string previewpath)
        {
            System.Drawing.Image img = null;
            System.Drawing.Image tempImage = null;
            System.Drawing.Image processed = null;
            try
            {
                string abspath = HttpContext.Current.Server.MapPath(imgpath);

                string absdestpath = HttpContext.Current.Server.MapPath(destpath);

                bool savetemp = !string.IsNullOrEmpty(previewpath);

                if (!File.Exists(abspath))
                {
                    throw new FileNotFoundException("未找到源图片");
                }
                else
                {
                    //检查目录
                    string dir = Path.GetDirectoryName(absdestpath);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    string abspreviewpath = "";
                    if (savetemp)
                    {
                        abspreviewpath = HttpContext.Current.Server.MapPath(previewpath);
                        dir = Path.GetDirectoryName(abspreviewpath);
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }

                    }
                    img = System.Drawing.Image.FromFile(abspath);
                    if (img.Width == properwidth && img.Height == properheight)
                    {
                        img.Save(absdestpath);

                        //保存临时图片
                        if (savetemp)
                        {
                            img.Save(abspreviewpath);
                        }
                    }
                    else
                    {
                        Process(img, properwidth, properheight, ref processed, ref tempImage);
                        //保存图片
                        processed.Save(absdestpath);

                        if (savetemp)
                        {
                            tempImage.Save(abspreviewpath);
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (img != null)
                {
                    img.Dispose();
                }
                if (processed != null)
                {
                    processed.Dispose();
                }
            }
        }

        /// <summary>
        /// 将图片的宽转为合适的尺寸
        /// </summary>
        /// <param name="imgpath">图片虚拟路径</param>
        /// <param name="properwidth">目标宽度</param>
        /// <param name="destpath">目标图片存储路径</param>
        public static void ImageToProperWidth(string imgpath, int properwidth, string destpath)
        {
            System.Drawing.Image img = null;
            System.Drawing.Image processed = null;
            try
            {
                string abspath = HttpContext.Current.Server.MapPath(imgpath);

                string absdestpath = HttpContext.Current.Server.MapPath(destpath);


                if (!File.Exists(abspath))
                {
                    throw new FileNotFoundException("未找到源图片");
                }
                else
                {
                    //检查目录
                    string dir = Path.GetDirectoryName(absdestpath);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    img = System.Drawing.Image.FromFile(abspath);
                    if (img.Width == properwidth)
                    {
                        img.Save(absdestpath);
                    }
                    else
                    {
                        processed = Process(img, properwidth);
                        //保存图片
                        processed.Save(absdestpath);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (img != null)
                {
                    img.Dispose();
                }
                if (processed != null)
                {
                    processed.Dispose();
                }
            }
        }








        //处理图片(按长宽比例)
        private static void Process(System.Drawing.Image img, int width, int height, ref System.Drawing.Image dest, ref System.Drawing.Image temp)
        {
            try
            {
                //返回要在画布中画出的图的矩形位置(占满整个画布)
                Rectangle destRec = new Rectangle(0, 0, width, height);
                //要画到画布中的原图的矩形位置（默认整个图片）
                Rectangle srcRec = new Rectangle(0, 0, img.Width, img.Height);

                //画布的大小
                int w = width;
                int h = height;

                //原图整体大于目标图
                if (img.Width >= width && img.Height >= height)
                {
                    //画布大于标准(w,h)
                    //源图片缩小到有一边符合标准(有一边大于目标尺寸，还需进行切图)

                    ///以据点比例较小的边为准

                    //宽所占比例较大
                    if ((double)img.Width / (double)img.Height >= (double)width / (double)height)
                    {
                        w = img.Width * height / img.Height;

                    }
                    //高所占比例较大
                    else
                    {
                        h = img.Height * width / img.Width;
                    }
                    destRec = new Rectangle(0, 0, w, h);
                }
                else
                {
                    //画布符合标准（width,height）

                    int destx = 0;
                    int desty = 0;
                    int destwidth = img.Width;
                    int destheight = img.Height;
                    //整体小于目标图,将图放在中央，实际返回的尺寸为目标图的尺寸
                    if (img.Width < width && img.Height < height)
                    {
                        //标准画布

                        //图形位于画布中央
                        destx = (width - img.Width) / 2;
                        desty = (height - img.Height) / 2;
                    }

                    ///以长边为准

                    //宽小于目标尺寸
                    else if (img.Width < width && img.Height > height)
                    {

                        //超出标准的一边缩小到标准
                        //小于标准的一边按比例缩小后再计算位置
                        destwidth = img.Width * height / img.Height;
                        destx = (width - destwidth) / 2;

                    }
                    //高小于目标尺寸
                    else if (img.Width > width && img.Height < height)
                    {
                        //同上
                        destheight = img.Height * width / img.Width;
                        desty = (height - destheight);
                    }
                    destRec = new Rectangle(destx, desty, destwidth, destheight);//画布左上角坐标为（0，0），矩形位置在画布中间

                }
                temp = DrawImage(img, w, h, destRec, srcRec);

                if (temp.Width > width || temp.Height > height)
                {
                    CutImage(temp, width, height, ref dest);
                }
                else
                {
                    dest = temp;
                }
            }
            catch (Exception)
            {
                throw;
            }

        }

        //处理图片(以宽为准)
        private static System.Drawing.Image Process(System.Drawing.Image img, int width)
        {
            try
            {
                //要在画布中画出的图的矩形位置
                Rectangle destRec = new Rectangle();

                //要画到画布中的原图的矩形位置（默认整个图片）
                Rectangle srcRec = new Rectangle(0, 0, img.Width, img.Height);

                //画布尺寸
                int w = 0;
                int h = 0;

                //原图整体大于目标图     (以宽为准)
                if (img.Width > width)
                {
                    w = width;
                    h = img.Height * width / img.Width;
                    destRec = new Rectangle(0, 0, w, h);//画出整张图片
                }
                else
                {
                    int destx = 0;
                    int desty = 0;
                    w = width;
                    h = img.Height;

                    destx = (width - img.Width) / 2;

                    destRec = new Rectangle(destx, desty, img.Width, img.Height);

                }
                return DrawImage(img, w, h, destRec, srcRec);
            }
            catch (Exception)
            {

                throw;
            }
            //不能释放资源，否则得到的结果将消失
        }

        //切图
        private static void CutImage(System.Drawing.Image img, int width, int height, ref System.Drawing.Image dest)
        {
            //有一边等于标准
            if (img.Width == width || img.Height == width)
            {
                //画布标准大小（width,height）=(w,h)
                int srcx = 0;
                int srcy = 0;
                srcx = (img.Width == width ? 0 : (img.Width - width) / 2);
                srcy = (img.Height == height ? 0 : (img.Height - height) / 2);

                //源图片切为符合标准大小
                dest = DrawImage(img, width, height, new Rectangle(0, 0, width, height), new Rectangle(srcx, srcy, width, height));
            }
        }

        //绘图
        private static System.Drawing.Image DrawImage(System.Drawing.Image img, int destwidth, int destheight, Rectangle destRec, Rectangle srcRec)
        {
            Bitmap bitmap = new Bitmap(destwidth, destheight);
            using (Graphics gps = Graphics.FromImage(bitmap))//读取画布到绘图对象
            {
                gps.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                gps.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                gps.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                gps.Clear(System.Drawing.Color.LightGray);
                gps.DrawImage(img, destRec, srcRec, GraphicsUnit.Pixel);
            }
            return bitmap;
            //不能释放bitmap资源，否则得到的结果将消失
        }



    }
}

